using DesktopWidgetApp.Core.Data;
using DesktopWidgetApp.UI.Helpers;
using DesktopWidgetApp.UI.Services;
using DesktopWidgetApp.Core.Services;
using DesktopWidgetApp.Shared;
using DesktopWidgetApp.UI.Helpers;
using DesktopWidgetApp.Core.Helpers;
using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using System.Windows.Interop;
using System.Threading.Tasks;

namespace DesktopWidgetApp.UI.Views
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly StatusService _statusService;
        private readonly IStatusRepository _statusRepository;
        private readonly Guid _currentUserId = new Guid("12345678-1234-1234-1234-123456789012"); // 临时用户ID
        private Point _startPoint;
        private DispatcherTimer _syncTimer;
        private TrayIconManager _trayIconManager;
        private StatusSyncHelper _statusSyncHelper;
        private DataSyncManager _dataSyncManager;

        public MainWindow()
        {
            InitializeComponent();

            // 使用DatabaseHelper获取数据库路径
            var databasePath = DatabaseHelper.GetDatabasePath();
            
            // 初始化状态仓储
            _statusRepository = new SqliteStatusRepository(databasePath);
            
            // 初始化状态服务
            _statusService = new StatusService(_statusRepository);

            // 初始化状态同步辅助类
            _statusSyncHelper = new StatusSyncHelper();

            // 初始化数据同步管理器
            _dataSyncManager = new DataSyncManager(_statusRepository, _statusSyncHelper);

            // 初始化托盘图标管理器
            _trayIconManager = new TrayIconManager(this);

            // 初始化UI
            InitializeUI();

            // 设置状态同步定时器
            SetupSyncTimer();

            // 设置窗口关闭事件
            this.Closing += MainWindow_Closing;

            // 应用当前样式
            ApplyCurrentStyle();

            // 监听样式变化事件
            StyleManager.StyleChanged += OnStyleChanged;
        }

        /// <summary>
        /// 窗口关闭事件处理
        /// </summary>
        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            // 取消关闭，改为隐藏窗口
            e.Cancel = true;
            this.Hide();
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            
            // 清理资源
            StyleManager.StyleChanged -= OnStyleChanged;
            
            if (_trayIconManager != null)
            {
                _trayIconManager.Dispose();
                _trayIconManager.OnDoubleClick -= _trayIconManager_OnDoubleClick;
            }
            
            if (_syncTimer != null)
            {
                _syncTimer.Stop();
                _syncTimer.Tick -= SyncTimer_Tick;
            }
        }

        /// <summary>
        /// 初始化用户界面
        /// </summary>
        private async void InitializeUI()
        {
            try
            {
                // 加载当前用户状态
                var currentStatus = await _statusService.GetUserCurrentStatusAsync(_currentUserId);
                if (currentStatus != null)
                {
                    UpdateStatusDisplay(currentStatus);
                }
                else
                {
                    // 默认设置为工作中状态
                    CurrentStatusText.Text = "工作中";
                    StatusIndicator.Fill = Brushes.Green;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化状态显示失败: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 设置状态同步定时器
        /// </summary>
        private void SetupSyncTimer()
        {
            _syncTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMinutes(1) // 每分钟同步一次
            };
            _syncTimer.Tick += async (sender, e) => await SyncStatusAsync();
            _syncTimer.Start();
        }

        private void ApplyCurrentStyle()
        {
            // 应用当前样式到窗口
            var styleSettings = StyleManager.GetCurrentStyleSettings();
            StyleManager.ApplyStyleToWindow(this, styleSettings);
        }

        private void OnStyleChanged(object sender, EventArgs e)
        {
            // 样式发生变化时，重新应用样式
            ApplyCurrentStyle();
        }

        private void SettingsButton_Click(object sender, RoutedEventArgs e)
        {
            // 打开设置窗口
            var settingsWindow = new SettingsWindow();
            settingsWindow.Owner = this;
            settingsWindow.ShowDialog();
        }

        private void TaskManagerButton_Click(object sender, RoutedEventArgs e)
        {
            // 打开任务管理窗口
            var taskManagerWindow = new TaskManagerWindow();
            taskManagerWindow.Owner = this;
            taskManagerWindow.ShowDialog();
        }

        /// <summary>
        /// 同步状态数据
        /// </summary>
        private async Task SyncStatusAsync()
        {
            try
            {
                // 使用DataSyncManager执行完整同步
                bool syncSuccess = await _dataSyncManager.PerformFullSyncAsync(_currentUserId);
                
                if (syncSuccess)
                {
                    // 同步成功，获取最新状态并更新UI
                    var currentStatus = await _statusService.GetUserCurrentStatusAsync(_currentUserId);
                    if (currentStatus != null)
                    {
                        UpdateStatusDisplay(currentStatus);
                        
                        // 更新托盘图标状态
                        if (_trayIconManager != null)
                        {
                            _trayIconManager.UpdateTrayIconStatus(currentStatus.IsDoNotDisturb);
                        }
                    }
                }
                else
                {
                    // 同步失败，检查网络连接
                    bool isConnected = await _statusSyncHelper.TestServerConnectionAsync();
                    if (!isConnected)
                    {
                        // 网络不可用，尝试同步待处理的更改
                        var pendingChangesCount = await _statusSyncHelper.SyncPendingChangesAsync();
                        if (pendingChangesCount > 0)
                        {
                            _trayIconManager?.ShowNotification("同步成功", $"成功同步了{pendingChangesCount}条待处理的状态更新");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // 同步失败不显示错误，避免打扰用户
                Console.WriteLine("状态同步失败: " + ex.Message);
            }
        }

        /// <summary>
        /// 更新状态显示
        /// </summary>
        private void UpdateStatusDisplay(Status status)
        {
            // 更新状态文本
            CurrentStatusText.Text = GetStatusDisplayName(status.Type);
            
            // 更新状态指示器颜色
            StatusIndicator.Fill = GetStatusColor(status.Type);
            
            // 更新免打扰开关
            DoNotDisturbToggle.IsChecked = status.IsDoNotDisturb;
            DoNotDisturbText.Text = status.IsDoNotDisturb ? "开" : "关";
        }

        /// <summary>
        /// 获取状态显示名称
        /// </summary>
        private string GetStatusDisplayName(StatusType statusType)
        {
            switch (statusType)
            {
                case StatusType.Working: return "工作中";
                case StatusType.InMeeting: return "会议中";
                case StatusType.OnBreak: return "休息中";
                case StatusType.OutOfOffice: return "外出";
                case StatusType.Custom: return "自定义";
                default: return "未知";
            }
        }

        /// <summary>
        /// 获取状态对应的颜色
        /// </summary>
        private Brush GetStatusColor(StatusType statusType)
        {
            switch (statusType)
            {
                case StatusType.Working: return Brushes.Green;
                case StatusType.InMeeting: return Brushes.Orange;
                case StatusType.OnBreak: return Brushes.Blue;
                case StatusType.OutOfOffice: return Brushes.Red;
                case StatusType.Custom: return Brushes.Purple;
                default: return Brushes.Gray;
            }
        }

        /// <summary>
        /// 标题栏鼠标按下事件 - 实现窗口拖动
        /// </summary>
        private void TitleBar_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                _startPoint = e.GetPosition(null);
                this.DragMove();
            }
        }

        /// <summary>
        /// 关闭按钮点击事件
        /// </summary>
        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            this.Hide(); // 隐藏窗口而不是关闭应用程序
        }

        /// <summary>
        /// 状态按钮点击事件
        /// </summary>
        private async void StatusButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var button = sender as FrameworkElement;
                if (button != null && Enum.TryParse<StatusType>(button.Tag.ToString(), out var statusType))
                {
                    var isDoNotDisturb = DoNotDisturbToggle.IsChecked ?? false;
                    
                    // 先更新本地状态
                    await _statusService.UpdateUserStatusAsync(
                        _currentUserId, 
                        statusType, 
                        isDoNotDisturb: isDoNotDisturb
                    );
                    
                    // 获取最新状态
                    var newStatus = await _statusService.GetUserCurrentStatusAsync(_currentUserId);
                    
                    if (newStatus != null)
                    {
                        // 通过同步助手同步到服务器
                        bool syncSuccess = await _statusSyncHelper.SyncStatusToServerAsync(newStatus);
                        
                        // 更新托盘图标状态
                        if (_trayIconManager != null)
                        {
                            _trayIconManager.UpdateTrayIconStatus(isDoNotDisturb);
                        }
                        
                        // 更新UI显示
                        UpdateStatusDisplay(newStatus);
                        
                        if (syncSuccess)
                        {
                            // 显示同步成功通知
                            _trayIconManager?.ShowNotification("状态更新成功", "您的工位状态已成功更新并同步");
                        }
                        else
                        {
                            // 显示同步失败通知
                            _trayIconManager?.ShowNotification("同步失败", "状态已更新但未能同步到服务器，将在网络恢复后重试", System.Windows.Forms.ToolTipIcon.Warning);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("更新状态失败: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 免打扰开关选中事件
        /// </summary>
        private async void DoNotDisturbToggle_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                DoNotDisturbText.Text = "开";
                await UpdateDoNotDisturbStatus(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("设置免打扰失败: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 免打扰开关取消选中事件
        /// </summary>
        private async void DoNotDisturbToggle_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                DoNotDisturbText.Text = "关";
                await UpdateDoNotDisturbStatus(false);
            }
            catch (Exception ex)
            {
                MessageBox.Show("取消免打扰失败: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 更新免打扰状态
        /// </summary>
        private async Task UpdateDoNotDisturbStatus(bool isDoNotDisturb)
        {
            // 获取当前用户状态
            var currentStatus = await _statusService.GetUserCurrentStatusAsync(_currentUserId);
            
            if (currentStatus != null)
            {
                // 更新本地免打扰状态
                await _statusService.UpdateUserStatusAsync(
                    _currentUserId, 
                    currentStatus.Type, 
                    currentStatus.CustomText, 
                    currentStatus.Color, 
                    isDoNotDisturb
                );
                
                // 获取更新后的状态
                var updatedStatus = await _statusService.GetUserCurrentStatusAsync(_currentUserId);
                
                if (updatedStatus != null)
                {
                    // 同步到服务器
                    bool syncSuccess = await _statusSyncHelper.SyncStatusToServerAsync(updatedStatus);
                    
                    // 更新托盘图标状态
                    if (_trayIconManager != null)
                    {
                        _trayIconManager.UpdateTrayIconStatus(isDoNotDisturb);
                    }
                    
                    if (syncSuccess)
                    {
                        _trayIconManager?.ShowNotification(
                            "免打扰状态更新成功", 
                            isDoNotDisturb ? "您已开启免打扰模式" : "您已关闭免打扰模式"
                        );
                    }
                    else
                    {
                        _trayIconManager?.ShowNotification(
                            "同步失败", 
                            "免打扰状态已更新但未能同步到服务器，将在网络恢复后重试", 
                            System.Windows.Forms.ToolTipIcon.Warning
                        );
                    }
                }
            }
            else
            {
                // 如果没有当前状态，创建一个新的工作中状态
                await _statusService.UpdateUserStatusAsync(
                    _currentUserId, 
                    StatusType.Working, 
                    isDoNotDisturb: isDoNotDisturb
                );
                
                // 获取新创建的状态
                var newStatus = await _statusService.GetUserCurrentStatusAsync(_currentUserId);
                
                if (newStatus != null)
                {
                    // 同步到服务器
                    await _statusSyncHelper.SyncStatusToServerAsync(newStatus);
                    
                    // 更新托盘图标状态
                    if (_trayIconManager != null)
                    {
                        _trayIconManager.UpdateTrayIconStatus(isDoNotDisturb);
                    }
                }
            }
        }


    }
}